package com.engine;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import javax.media.CannotRealizeException;
import javax.media.ControllerEvent;
import javax.media.ControllerListener;
import javax.media.EndOfMediaEvent;
import javax.media.Manager;
import javax.media.NoPlayerException;
import javax.media.Player;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;


public class VideoPanel extends JPanel implements MouseListener,ControllerListener,Runnable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Player mediaPlayer;
	private File file;
	private Dimension screen=Toolkit.getDefaultToolkit().getScreenSize();
	private Component control;
	private Component video; 
	private String []strFiles;
	private int idx=0;
	private float volume=1.0f;
	
	public void save()
	{
		try {
			SaveConfig.getInstance(null);
			SaveConfig.PUT("VOLUME",String.valueOf(mediaPlayer.getGainControl().getLevel()));
			SaveConfig.Close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
		}
		
	}
	public VideoPanel(float volume){
		this.volume=volume;
		/*
		File file = new File("video");
		File[] files = file.listFiles();
		strFiles=new String[files.length];
		int index=0;
		for(File fl: files)
		{
			strFiles[index]=fl.getAbsolutePath();
			index++;
			
		}
		*/
		
		int countVideo=ReadConfig.toInt("VIDEO_COUNTER");
		if(countVideo<0) return;
		String[] videoItems =ReadConfig.GET("VIDEO_FILE").split("\\|");
		strFiles=new String[countVideo];
		for(int i=0; i < countVideo;i++)
		{
			strFiles[i] = "video/" + videoItems[i]; 
		}
		
		idx=0;
		while(!isFileExist(strFiles[idx]))
		{
			idx++;
		}
		playing(strFiles[idx],volume);
		
	}
	
	private boolean isFileExist(String filename)
	{
		File file=new File(filename);
		return file.exists();
	}
	
	public VideoPanel(String videoFile,float volume)
	{
		this.volume=volume;
		playing(videoFile,volume);
	}
	private void playing(String videoFile,float volume){
	        setOpaque(false);
	        file = new File(videoFile); 
	        setLayout( new BorderLayout() );      
	        Manager.setHint( Manager.LIGHTWEIGHT_RENDERER, true );
	        this.setSize(600, 600);
	        this.setPreferredSize(new Dimension(screen.width -340,screen.height-110));
	        this.setVisible(true);
	        URL mediaURL=null;
	        try {
				mediaURL=file.toURI().toURL();
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
				return;
			}
	        try{
	            mediaPlayer = Manager.createRealizedPlayer( mediaURL );
	            video = mediaPlayer.getVisualComponent();
	            video.addMouseListener(this);
	            control = mediaPlayer.getControlPanelComponent();
	            if(video != null) 
	                    add(video,BorderLayout.CENTER );
	            if(control!=null)
	            	add(control,BorderLayout.SOUTH);
	            mediaPlayer.getGainControl().setLevel( volume);
	            mediaPlayer.realize();
	            mediaPlayer.start();
	            mediaPlayer.addControllerListener(this);
	            video.validate();
	            video.repaint();
	            SwingUtilities.invokeLater(new Runnable(){
	            	public void run()
	            	{
	            		control.setVisible(false);
	            		control.validate();
		                control.repaint();
	            	}
	            });
		    }
		    catch ( NoPlayerException noPlayerException ){
		            System.err.println( "No media player found" );
		    }
		    catch ( CannotRealizeException cannotRealizeException ){
		            System.err.println( "Could not realize media player" );
		    }
		    catch ( IOException iOException ){
		            System.err.println( "Error reading from the source" );
		    }
	        
	}
	public void stopPlay(){         
	        mediaPlayer.stop();
	}
	public void mouseClicked(MouseEvent arg0) {
		// TODO Auto-generated method stub
		if(arg0.getClickCount()==2)
		{
			if(!control.isVisible())
				control.setVisible(true);
			else
				control.setVisible(false);
		}
	}
	public void mousePressed(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}
	public void mouseReleased(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}
	public void mouseEntered(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}
	public void mouseExited(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}
	public void controllerUpdate(ControllerEvent arg0) {
		// TODO Auto-generated method stub
		if(arg0 instanceof EndOfMediaEvent)
		{
			mediaPlayer.stop();	
			idx++;
			if(idx==strFiles.length)
				idx=0;
			
			while(!isFileExist(strFiles[idx]))
			{
				idx++;
			}
			
			new Thread(this).start();
		}
		
	}
	public void run() {
		// TODO Auto-generated method stub
		this.remove(video);
		this.remove(control);
		playing(strFiles[idx],volume);
	}

	public void windowOpened(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	public void windowClosing(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	public void windowClosed(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	public void windowIconified(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	public void windowDeiconified(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	public void windowActivated(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	public void windowDeactivated(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}
}